package com.aaa.mysecurity.config;

import cn.hutool.json.JSONUtil;
import com.aaa.mysecurity.filter.MyFilter;
import com.aaa.mysecurity.util.JwtUtil;
import com.aaa.mysecurity.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.PrintWriter;
import java.nio.file.AccessDeniedException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：ludi（206913808@qq.com）
 * @date ：Created in 2022/11/1 15:49
 * @description：
 * @modified By：
 * @version:
 */
@Configuration
public class MyConfig {

    @Autowired
    MyFilter myFilter;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.addFilterBefore(myFilter, UsernamePasswordAuthenticationFilter.class);
        http.formLogin()
                //.loginPage("/login.html")
                .loginProcessingUrl("/login")
                //.successForwardUrl("/success")
                .successHandler(successHandler())
                .permitAll();
        //允许跨域
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
        http.cors();
        //禁止跨域伪造
        http.csrf().disable();
        http.authorizeRequests().anyRequest().authenticated();
        return http.build();
    }

    public AuthenticationSuccessHandler successHandler() {
        return (request, response, authentication) -> {
            response.setContentType("application/JSON,character=utf-8");
            PrintWriter writer = response.getWriter();
            User principal = (User) authentication.getPrincipal();
            String username = principal.getUsername();
            Collection<GrantedAuthority> authorities = principal.getAuthorities();
            List<String> collect = authorities.stream().map(item -> item.getAuthority()).collect(Collectors.toList());
            Map<String,Object> map = new HashMap<>();
            map.put("username", username);
            map.put("authorities", collect);
            String jwt = JwtUtil.createJWT(map);
            Result result = new Result(200, "成功", jwt);
            String s = JSONUtil.toJsonStr(result);
            writer.println(s);
            writer.flush();
            writer.close();
        };
    }

    /**
     * @create by: ludi（206913808@qq.com）
     * @description: 权限不足的处理
     * @create time: 2022/11/4 22:19
     * @param
     * @return org.springframework.security.web.access.AccessDeniedHandler
     */
    private AccessDeniedHandler accessDeniedHandler(){
        return ((request,response,accessDeniedException)->{
            response.setContentType("application/JSON,character=utf-8");
            PrintWriter writer = response.getWriter();
            Result result = new Result(403, "权限不足", null);

            String s = JSONUtil.toJsonStr(result);
            writer.println(s);
            writer.flush();
            writer.close();
        });
    }
}